<template>
  <treeselect class="tree-select" :style="{ width: width + 'px', height: height + 'px', lineHeight: height + 'px', }" :append-to-body="true" :show-count="true" :flat="true" :clearable="clearable" v-model="deptId" :options="treeData" :normalizer="normalizer" placeholder="请选择试验室"></treeselect>
</template>
<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "DeptTreeSelect",
  components: {
    Treeselect
  },
  props: {
    // 树结构数据
    data: {
      type: Array,
      default() {
        return [];
      }
    },
    width: {
      type: Number,
      default() {
        return 255;
      }
    },
    height: {
      type: Number,
      default() {
        return 32;
      }
    },
    value: {
      type: String,
      default() {
        return null;
      }
    },
    /**是否展示清空按钮 */
    clearable: {
      type: Boolean,
      default() {
        return false;
      }
    }
  },
  data() {
    return {};
  },
  computed: {
    treeData: {
      get() {
        return this.$store.state.dept.deptTreeList;
      }
    },
    deptId: {
      get() {
        return this.$store.state.dept.deptId;
      },
      set(val) {
        this.$store.dispatch("changeDeptId", val);
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.labFlag && node.labFlag == 1) {
        node.isDisabled = false;
      } else {
        node.isDisabled = true;
      }
      return {
        ...node,
        id: node.id,
        label: node.label,
        children: node.children
      };
    },
    // handleTreeData (data) {
    //   return data.map(item => {
    //     if (item.children) {
    //       item.children = this.handleTreeData(item.children)
    //     }
    //     return item
    //   })
    // },
    /** 逐级获取父节点名称 by winterwa -- start ---*/
    findParentPath(nodeId, options, path = []) {
      for (const option of options) {
        if (option.id === nodeId) {
          return [...path, option.label];
        }
        if (option.children) {
          const childPath = this.findParentPath(nodeId, option.children, [...path, option.label]);
          if (childPath) {
            return childPath;
          }
        }
      }
      return null;
    },
    onNodeSelect(nodeId) {
      if (!nodeId) {
        return;
      }
      const path = this.findParentPath(nodeId, this.treeData);
      if (path) {
        const joinedPath = path.join("/");
        // console.log(joinedPath) // 用“/”拼接并输出父节点名称
        this.deptName = joinedPath;
      }
    }
    /** 逐级获取父节点名称 by winterwa -- end ---*/
  }
};
</script>
<style lang="scss" scoped></style>
